package com.naihe.anderson.sms.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.ContactsContract.Data;
import android.text.TextUtils;

import com.naihe.anderson.sms.dbhelper.NhSmsDBHelper;
import com.naihe.anderson.sms.entity.ContactUser;
import com.naihe.anderson.sms.entity.Nhsms;
import com.naihe.anderson.sms.entity.NhsmsSession;
import com.naihe.anderson.sms.util.FileUtil;
import com.naihe.anderson.sms.util.ImageUtil;
import com.naihe.anderson.sms.util.ObjectUtil;
import com.naihe.anderson.sms.util.Pinyin;

public class SystemDao {
	Context context;
	
	ContentResolver contentResolver;
	private Map<String, Integer> numberTypeMap = new HashMap<String, Integer>();// <String
																				// phonenumber,
																				// String
																				// phonenumberType>
	private Map<String, Long> numberMatchContactIdMap = new HashMap<String, Long>();// <String
																						// phoneNumber,
																						// String
																						// contactId>
	private Map<Long, Bitmap> contactHeadImgMap = new HashMap<Long, Bitmap>();// <Long
																					// photoId，
																					// Bitmap
																					// 头像>
	
//	private Map<Long, ContactUser> contactUserMap = new HashMap<Long, ContactUser>();// <Long
//																						// contactId，
//																						// ContactUser
	
	public SystemDao(Context context) {
		this.context = context;
		contentResolver = context.getContentResolver();
	}

	public List<ContactUser> getContactUserListFromSys(){
		contactHeadImgMap.clear();
		List<ContactUser> list = new ArrayList<ContactUser>();
		
		String[] CONTACT_COLUMNS = new String[] {
				ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
				ContactsContract.CommonDataKinds.Phone.TYPE,
				ContactsContract.CommonDataKinds.Phone.DATA1,
				ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
				ContactsContract.CommonDataKinds.Phone.PHOTO_ID,
				"account_name",
				};
		
		Cursor phones = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, CONTACT_COLUMNS,
				null, 
				null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
		long contact_id_pre = -1;
		ContactUser contactUser = new ContactUser();
		if(phones != null && phones.moveToFirst()){
			for (int i = 0; i < phones.getCount(); i++) {
				long contact_id = phones.getLong(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
				String phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA1));
				Integer type = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
				String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
				long photoId = phones.getLong(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_ID));
				if(!TextUtils.isEmpty(phone)){
					phone = ObjectUtil.phoneNumberFormat(phone);
					numberTypeMap.put(phone, type);
				}
					
				if(contact_id_pre != -1 && contact_id != contact_id_pre){
		        	if(contactUser.getNumberList() != null){
		        		for (int j = 0; j < contactUser.getNumberList().size(); j++) {
							numberMatchContactIdMap.put(contactUser.getNumberList().get(j), contactUser.getContactId());
						}
		        		contactUser.setNumbers(contactUser.getNumberList().toString().replace("[", "").replace("]", ""));
		        	}
		        	
//		        	if(!TextUtils.isEmpty(contactUser.getPhotoId())){
//		    			Bitmap photoBitmap = null;
//		    			String[] COLUMNS = new String[] {Photo.PHOTO};
//		    		    Cursor pcursor = contentResolver.query(ContentUris.withAppendedId(Data.CONTENT_URI, Long.parseLong(contactUser.getPhotoId())), COLUMNS,
//		    		        		null, null, null);
//		    		    if (pcursor != null && pcursor.moveToFirst() && !pcursor.isNull(0)) {
//		    		    	byte[] photoData = pcursor.getBlob(0);
//		    		    	//图片压缩
//		    		    	photoBitmap = ImageUtil.compressPhoto(photoData, 50);
//		    		    	contactHeadImgMap.put(contactUser.getContactId(), photoBitmap);
//		    		    	pcursor.close();
//		    		    }
//		    		}
		        	list.add(contactUser);
//		        	contactUserMap.put(contactUser.getContactId(), contactUser);
		        	contactUser = new ContactUser();
				}
				
				if(!TextUtils.isEmpty(phone)){
					contactUser.getNumberList().add(phone);
				}
				contactUser.setName(name);
				contactUser.setContactId(contact_id);
				contactUser.setChineseNameCode(Pinyin.getPinYinHeadChar(name, context).toUpperCase());
				contactUser.setPhotoId(photoId);
				
				contact_id_pre = contact_id;
				phones.moveToNext();
			}
			phones.close();
		}
	    
		return list;
	}
	
	/**
	 * 获取短信数量
	 * @return
	 */
	public int getSystemSmsCount(){
		Uri uri = Uri.parse(Nhsms.SMS_URI_ALL);
		int tCount = -1;
		try {
			Cursor smscur = contentResolver.query(uri, NhSmsDBHelper.nhsms_projection_id, null, null, null);
			
			if (smscur != null) {
				tCount = smscur.getCount();
			}else{
				tCount = -1;
			}
			
			smscur.close();
		} catch (Exception e) {
			FileUtil.addLog("SystemDao::getSystemSmsCount", SystemDao.class, "SystemDao", e);
		} finally{
			
		}	
		FileUtil.addLog("SystemDao::getSystemSmsCount tCount="+tCount, SystemDao.class, "SystemDao", null);
		return tCount;
	}
	public List<Nhsms> getSystemSms(){
		Uri uri = Uri.parse(Nhsms.SMS_URI_ALL);
		List<Nhsms> list = new ArrayList<Nhsms>();
		
		try{
			Cursor smscur = contentResolver.query(uri, NhSmsDBHelper.nhsms_projection, null, null, Nhsms.DATE + " desc");      // 获取手机内部短信 
			if(smscur != null && smscur.moveToFirst()){
				for (int i = 0; i < smscur.getCount(); i++) {
					Nhsms nhsms = new Nhsms();
					nhsms.set_id(smscur.getLong(smscur.getColumnIndex(Nhsms._ID)));
					nhsms.setAddress(ObjectUtil.phoneNumberFormat(smscur.getString(smscur.getColumnIndex(Nhsms.ADDRESS))));
					nhsms.setBody(smscur.getString(smscur.getColumnIndex(Nhsms.BODY)));
					nhsms.setDate(smscur.getLong(smscur.getColumnIndex(Nhsms.DATE)));
					nhsms.setDate_sent(smscur.getLong(smscur.getColumnIndex(Nhsms.DATE_SENT)));
					nhsms.setError_code(smscur.getInt(smscur.getColumnIndex(Nhsms.ERROR_CODE)));
					nhsms.setLocked(smscur.getInt(smscur.getColumnIndex(Nhsms.LOCKED)));
					nhsms.setPerson(smscur.getLong(smscur.getColumnIndex(Nhsms.PERSON)));
					nhsms.setProtocol(smscur.getInt(smscur.getColumnIndex(Nhsms.PROTOCOL)));
					nhsms.setRead(smscur.getInt(smscur.getColumnIndex(Nhsms.READ)));
					nhsms.setReply_path_present(smscur.getInt(smscur.getColumnIndex(Nhsms.REPLY_PATH_PRESENT)));
					nhsms.setSeen(smscur.getInt(smscur.getColumnIndex(Nhsms.SEEN)));
					nhsms.setService_center(smscur.getString(smscur.getColumnIndex(Nhsms.SERVICE_CENTER)));
					nhsms.setStatus(smscur.getInt(smscur.getColumnIndex(Nhsms.STATUS)));
					nhsms.setSubject(smscur.getString(smscur.getColumnIndex(Nhsms.SUBJECT)));
					nhsms.setThread_id(smscur.getLong(smscur.getColumnIndex(Nhsms.THREAD_ID)));
					nhsms.setType(smscur.getInt(smscur.getColumnIndex(Nhsms.TYPE)));
					
					list.add(nhsms);
					smscur.moveToNext();
				}
				smscur.close();
			}
		}catch (Exception e) {
			FileUtil.addLog("SystemDao::getSystemSms", SystemDao.class, "SystemDao", e);
		}
		
		return list;
	}
	
	public long getSystemSmsTid(long smsId){
		Uri uri = Uri.parse(Nhsms.SMS_URI_ALL);
		long sessionId = -1;
		try{
			Cursor smscur = contentResolver.query(uri, NhSmsDBHelper.nhsms_projection_id, "_id=?", new String[]{"" + smsId}, Nhsms.DATE + " desc");      // 获取手机内部短信 
			if(smscur != null && smscur.moveToFirst()){
				sessionId = smscur.getLong(smscur.getColumnIndex(Nhsms.THREAD_ID));
				smscur.close();
			}
		}catch (Exception e) {
			FileUtil.addLog("SystemDao::getSystemSmsTid", SystemDao.class, "SystemDao", e);
		}
		
		return sessionId;
	}
	
	public long[] getSystemInfoId(String body){
		Uri uri = Uri.parse(Nhsms.SMS_URI_ALL);
		long[] sessionId = {-1,-1};
		try{
			Cursor smscur = contentResolver.query(uri, NhSmsDBHelper.nhsms_projection_id, "body=?", new String[]{body}, Nhsms.DATE + " desc");      // 获取手机内部短信 
			if(smscur != null && smscur.moveToFirst()){
				sessionId[0] = smscur.getLong(smscur.getColumnIndex(Nhsms.THREAD_ID));
				sessionId[1] = smscur.getLong(smscur.getColumnIndex(Nhsms._ID));
				smscur.close();
			}
		}catch (Exception e) {
			FileUtil.addLog("SystemDao::getSystemInfoId", SystemDao.class, "SystemDao", e);
		}
		
		return sessionId;
	}
	
	public void deleteSystemSmsByid(long systemSmsId, long smsId){
		try {
			int sLen = contentResolver.delete(Uri.parse("content://sms/conversations/" + systemSmsId), "_id=?", new String[]{"" + smsId});
			FileUtil.addLog("SystemDao::deleteSystemSmsByid backCount=" + sLen, SystemDao.class, "SystemDao", null);
	    } catch (Exception e) {  
	    	FileUtil.addLog("SystemDao::deleteSystemSmsByid", SystemDao.class, "SystemDao", e);
	    } 
	}
	
	public void deleteSystemSmsByTid(long systemSmsId){
		try {
			int sLen = contentResolver.delete(Uri.parse("content://sms/conversations/" + systemSmsId), null, null);
			FileUtil.addLog("SystemDao::deleteSystemSmsByTid backCount=" + sLen, SystemDao.class, "SystemDao", null);
	    } catch (Exception e) {  
	    	FileUtil.addLog("SystemDao::deleteSystemSmsByTid", SystemDao.class, "SystemDao", e);
	    } 
	}
	
	public long addSystemSms(Nhsms nhsms){
		try {
			ContentValues contentValues = new ContentValues();
			contentValues.put(Nhsms.ADDRESS, nhsms.getAddress());
			contentValues.put(Nhsms.BODY, nhsms.getBody());
			contentValues.put(Nhsms.DATE, nhsms.getDate());
			contentValues.put(Nhsms.DATE_SENT, nhsms.getDate_sent());
			contentValues.put(Nhsms.ERROR_CODE, nhsms.getError_code());
			contentValues.put(Nhsms.LOCKED, nhsms.getLocked());
			contentValues.put(Nhsms.PERSON, nhsms.getPerson());
			contentValues.put(Nhsms.PROTOCOL, nhsms.getProtocol());
			contentValues.put(Nhsms.READ, nhsms.getRead());
			contentValues.put(Nhsms.REPLY_PATH_PRESENT, nhsms.getReply_path_present());
			contentValues.put(Nhsms.SEEN, nhsms.getSeen());
			contentValues.put(Nhsms.SERVICE_CENTER, nhsms.getService_center());
			contentValues.put(Nhsms.STATUS, Nhsms.STATUS_NONE);
			contentValues.put(Nhsms.SUBJECT, nhsms.getSubject());
//			contentValues.put(Nhsms.THREAD_ID, nhsms.getThread_id());
			contentValues.put(Nhsms.TYPE, nhsms.getType());
			Uri uri = contentResolver.insert(Uri.parse("content://sms/"), contentValues);
			
			return Long.parseLong(uri.getEncodedPath().substring(1));
	    } catch (Exception e) {  
	    	FileUtil.addLog("SystemDao::addSystemSms", SystemDao.class, "SystemDao", e);
	    } 
		
		return -1;
	}
	
	public void updateSystemSms(Nhsms nhsms){
		try {
			ContentValues contentValues = new ContentValues();
			contentValues.put(Nhsms.ADDRESS, nhsms.getAddress());
			contentValues.put(Nhsms.BODY, nhsms.getBody());
			contentValues.put(Nhsms.DATE, nhsms.getDate());
			contentValues.put(Nhsms.DATE_SENT, nhsms.getDate_sent());
			contentValues.put(Nhsms.ERROR_CODE, nhsms.getError_code());
			contentValues.put(Nhsms.LOCKED, nhsms.getLocked());
			contentValues.put(Nhsms.PERSON, nhsms.getPerson());
			contentValues.put(Nhsms.PROTOCOL, nhsms.getProtocol());
			contentValues.put(Nhsms.READ, nhsms.getRead());
			contentValues.put(Nhsms.REPLY_PATH_PRESENT, nhsms.getReply_path_present());
			contentValues.put(Nhsms.SEEN, nhsms.getSeen());
			contentValues.put(Nhsms.SERVICE_CENTER, nhsms.getService_center());
			contentValues.put(Nhsms.STATUS, nhsms.getStatus());
			contentValues.put(Nhsms.SUBJECT, nhsms.getSubject());
			contentValues.put(Nhsms.THREAD_ID, nhsms.getThread_id());
			contentValues.put(Nhsms.TYPE, nhsms.getType());
			int sLen = contentResolver.update(Uri.parse("content://sms/"), contentValues, "_id=?", new String[]{"" + nhsms.get_id()});
			FileUtil.addLog("SystemDao::updateSystemSms backCount="+sLen, SystemDao.class, "SystemDao", null);
	    } catch (Exception e) {  
	    	FileUtil.addLog("SystemDao::updateSystemSms", SystemDao.class, "SystemDao", e);
	    } 
	}
	
	public void updateSystemReadSms(NhsmsSession nhsmsSession){
		try {
			ContentValues contentValues = new ContentValues();
			contentValues.put(Nhsms.READ, nhsmsSession.getRead());
			
			int sLen = contentResolver.update(Uri.parse("content://sms/"), contentValues, "thread_id=?", new String[]{"" + nhsmsSession.getTid()});
			FileUtil.addLog("SystemDao::updateSystemReadSms backCount="+sLen, SystemDao.class, "SystemDao", null);
	    } catch (Exception e) {  
	    	FileUtil.addLog("SystemDao::updateSystemReadSms", SystemDao.class, "SystemDao", e);
	    } 
	}
	
	public Long getContactIdByPhoneNum(String phoneNum){
		return numberMatchContactIdMap.get(phoneNum);
	}
	
	public Integer getPhoneNumType(String phoneNum){
		return numberTypeMap.get(phoneNum);
	}
	
	public Bitmap getContactHeadImgByPhontoId(Long photoId){
		if(photoId <= 0) return null;
		
		Bitmap photoBitmap = contactHeadImgMap.get(photoId);
		
		if(contactHeadImgMap.get(photoId) == null){
			String[] COLUMNS = new String[] {Photo.PHOTO};
		    Cursor pcursor = contentResolver.query(ContentUris.withAppendedId(Data.CONTENT_URI, photoId), COLUMNS, null, null, null);
		    if (pcursor != null && pcursor.moveToFirst() && !pcursor.isNull(0)) {
		    	byte[] photoData = pcursor.getBlob(0);
		    	//图片压缩
		    	photoBitmap = ImageUtil.compressPhoto(photoData, 50);
		    	contactHeadImgMap.put(photoId, photoBitmap);
		    	pcursor.close();
		    }
		}
		return photoBitmap;
	}
	
}
